package mylab.starters.mybatis.support.dynamicTable.impl;

import cn.hutool.core.lang.Assert;
import mylab.starters.mybatis.support.dynamicTable.AutoCreatedTableNameHandler;

/**
 * 按id取模分表处理器:[TABLE_suffix]
 */
public class IdModTableNameHandler extends AutoCreatedTableNameHandler {
    private Integer mod;

    //使用ThreadLocal防止多线程相互影响
    private static ThreadLocal<Integer> id = new ThreadLocal<>();

    public static void setId(Integer idValue) {
        id.set(idValue);
    }

    public IdModTableNameHandler() {
        this(10);
    }

    public IdModTableNameHandler(Integer modValue) {
        mod = modValue;
    }

    @Override
    protected String getDynamicTableName(String sql, String tableName) {
        Integer idValue = id.get();
        Assert.notNull(idValue, "IdModTableNameHandler need setId");

        String suffix = String.valueOf(idValue % mod);
        //这里清除ThreadLocal的值，防止线程复用出现问题
        id.remove();
        return tableName + "_" + suffix;
    }
}
